﻿using FileManagerSystem.DbInfos;
using FileManagerSystem.Extend;
using FileManagerSystem.LiteDb;
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace FileManagerSystem.Repository
{
    /// <summary>
    /// Dao仓库类通用实现，增删改查，如果要实现自定义的事务功能，请去对应的Interface中提供事务接口，并在实现类中实现对应事务
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new()
    {
        /// <summary>
        /// 注入的dbContext
        /// </summary>
        [Autowired]
        public ILiteDbContext _liteDb { get; set; }

        #region 查询
        /// <summary>
        /// 查询全部 --不分页
        /// </summary>
        /// <returns></returns>
        public virtual async Task<List<TEntity>> FindAll(Expression<Func<TEntity, bool>> expression)
        {
            return await Task.Run(() =>
            {
                var result = _liteDb.DbContext.GetCollection<TEntity>()
                .Find(expression);
                return result.ToList();
            });
        }

        /// <summary>
        /// 查询指定多条 --分页
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public virtual async Task<TEntityPaged<TEntity>> FindAllToPage(Expression<Func<TEntity, bool>> expression, int page, int size)
        {
            return await Task.Run(() =>
            {
                var total = _liteDb.DbContext.GetCollection<TEntity>()
                .Count(expression);
                var result = _liteDb.DbContext.GetCollection<TEntity>()
                    .Find(expression, (page - 1) * size, size);
                return new TEntityPaged<TEntity>()
                {
                    Datas = result.ToList(),
                    Total = total
                };
            });

        }

        /// <summary>
        /// 查询指定一条
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<TEntity> FindOne(Expression<Func<TEntity, bool>> expression)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>()
                .FindOne(expression);
            });
        }

        /// <summary>
        /// 检查对象是否存在
        /// </summary>
        /// <param name="expression"></param>
        /// <returns></returns>
        public async Task<bool> FindExist(Expression<Func<TEntity, bool>> expression)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>()
                .Exists(expression);
            });
        }
        #endregion

        #region 新增
        /// <summary>
        /// 单条新增 id模式
        /// </summary>
        /// <param name="forecast"></param>
        /// <returns></returns>
        public async Task<BsonValue> Insert(TEntity forecast)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>()
                .Insert(forecast);
            });
        }

        /// <summary>
        /// 单条新增 ObjectId+Guid模式
        /// </summary>
        /// <param name="forecast"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<BsonValue> Insert(TEntity forecast, BsonAutoId type)
        {
            return await Task.Run(() =>
            {
                var bsonVal = new BsonValue();
                bsonVal = type switch
                {
                    BsonAutoId.Int32 => throw new Exception("please use #Insert(TEntity forecast)# instead."),
                    BsonAutoId.Int64 => throw new Exception("please use #Insert(TEntity forecast)# instead."),
                    BsonAutoId.ObjectId => new BsonValue(ObjectId.NewObjectId()),
                    BsonAutoId.Guid => new BsonValue(Guid.NewGuid()),
                    _ => throw new Exception("please use #Insert(TEntity forecast)# instead."),
                };
                _liteDb.DbContext.GetCollection<TEntity>()
                   .Insert(bsonVal, forecast);
                return bsonVal;
            });

        }

        /// <summary>
        /// 多条新增 id模式
        /// </summary>
        /// <param name="forecast"></param>
        /// <returns></returns>
        public async Task<int> BulkInsert(List<TEntity> forecast)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>()
                .InsertBulk(forecast);
            });
        }
        #endregion

        #region 更新
        /// <summary>
        /// 单条更新
        /// </summary>
        /// <param name="forecast"></param>
        /// <returns></returns>
        public async Task<bool> Update(TEntity forecast)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>().Update(forecast);
            });
        }

        /// <summary>
        /// 异步单条更新
        /// </summary>
        /// <param name="forecast"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(TEntity forecast)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>().Update(forecast);
            });
        }
        #endregion

        #region 删除
        /// <summary>
        /// 单条删除 Guid
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<bool> Delete(BsonValue id)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>()
                .Delete(id);
            });
        }

        /// <summary>
        /// 多条删除
        /// </summary>
        /// <param name="expression">删除条件</param>
        /// <returns></returns>
        public async Task<int> DeleteMany(Expression<Func<TEntity, bool>> expression)
        {
            return await Task.Run(() =>
            {
                return _liteDb.DbContext.GetCollection<TEntity>().DeleteMany(expression);
            });
        }
        #endregion

        #region 委托事务
        /// <summary>
        /// 异步事务
        /// </summary>
        /// <param name="action">委托内容</param>
        /// <returns></returns>
        public async Task<bool> TransAsync(Action action)
        {
            return await Task.Run(() =>
            {
                try
                {
                    _liteDb.DbContext.BeginTrans();
                    action.Invoke();
                    return _liteDb.DbContext.Commit();
                }
                catch (Exception ex)
                {
                    _liteDb.DbContext.Rollback();
                    throw ex;
                }
            });
        }
        #endregion
    }
}
